package com.accp.controller;


import com.accp.common.AjaxRtn;
import com.accp.common.Pager;
import com.accp.config.PubConfig;
import com.accp.model.EduScratch;
import com.accp.service.ScratchService;
import com.accp.util.SerialNumUtil;
import com.accp.util.date.DateUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 尚晓忠 on 2019/3/8 20:55:38
 */
@RestController
@Api(tags = "scratch中心")
public class ScratchController {
    Logger logger= LoggerFactory.getLogger(ScratchController.class);
    private final PubConfig pubConfig;
    @Autowired
    private ScratchService scratchService;

    @Autowired
    public ScratchController(PubConfig pubConfig) {
        this.pubConfig = pubConfig;
    }


    @RequestMapping(value = "/scratchSave", method = RequestMethod.POST)
    @ApiOperation(value = "保存作品",notes ="保存作品")
    public AjaxRtn scratchSave(HttpServletRequest request, HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        try {
            String uploadPath = pubConfig.getImageUploadPath();
            String storePath = "/scratch/" + DateUtil.getShortSystemDate() + "/";
            String userId=request.getHeader("userId");
            MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;//request强制转换注意
            List<MultipartFile> files = mRequest.getFiles("files");
            String title="";
            String scratchPic="";
            String scratchUrl="";
            for(int i=0;i<files.size();i++ ){
                //获取文件路径
                if(i==0){
                    String newFileName = DateUtil.getShortSystemTime() + SerialNumUtil.createRandowmNum(6) + "." + "png";
                    File file1 = new File(uploadPath + storePath,newFileName);
                    //如果目录不存在，则创建
                    if (!file1.getParentFile().exists()) {
                        file1.getParentFile().mkdirs();
                    }
                    files.get(i).transferTo(file1);
                    scratchPic=storePath+newFileName;
                }else if(i==1){
                    title= files.get(i).getOriginalFilename();
                    String newFileName = DateUtil.getShortSystemTime() + SerialNumUtil.createRandowmNum(6) + "." + "sb3";
                    File file1 = new File(uploadPath + storePath,newFileName);
                    //如果目录不存在，则创建
                    if (!file1.getParentFile().exists()) {
                        file1.getParentFile().mkdirs();
                    }
                    files.get(i).transferTo(file1);
                    scratchUrl=storePath+newFileName;
                }
            }
                EduScratch scratch=new EduScratch();
                scratch.setScratchName(title);
                scratch.setScratchPic(scratchPic);
                scratch.setScratchUrl(scratchUrl);
                scratch.setUserId(Integer.parseInt(userId));
                scratchService.save(scratch);
            return new AjaxRtn(true,"保存成功");
        } catch (Exception e) {
            logger.error("scratch/practice/upload_screenshot()--error", e);
            return new AjaxRtn(false,"异常");
        }

    }


    @RequestMapping(value = "/scratchList", method = RequestMethod.POST)
    @ApiOperation(value = "作品列表",notes ="作品列表")
    public AjaxRtn scratchList(@RequestBody Pager pager) {
        System.out.println(pubConfig.getImageUploadPath());
        Map<String,Object> result=new HashMap<>(16);
        PageHelper.startPage(pager.getPage(),pager.getRows());
        List<EduScratch> scratches=scratchService.selectList(null);
        PageInfo<EduScratch> pageInfo = new PageInfo<>(scratches);
        result.put("curPage", pager.getPage());
        result.put("pageSize", pager.getRows());
        result.put("count", pageInfo.getTotal());
        result.put("litems", pageInfo.getList());
        return new AjaxRtn(true,"ok",result);

    }




}
